package com.zhengsr.latte.net.download;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.zhengsr.latte.app.Latte;
import com.zhengsr.latte.net.RestClient;
import com.zhengsr.latte.utils.FileUtil;

import java.io.File;
import java.io.InputStream;

import okhttp3.ResponseBody;

/**
 * Created by zhengshaorui on 2018/4/11.
 * 该类用来写文件
 */

public class SaveFileTask extends AsyncTask<Object,Void,File>{

    RestClient.Builder builder ;


    @Override
    protected File doInBackground(Object... objects) {
        builder = (RestClient.Builder) objects[0];
        ResponseBody body = (ResponseBody) objects[1];
        if (builder != null){
            InputStream is = body.byteStream();
            if (TextUtils.isEmpty(builder.downloadDir) || builder.downloadDir.equals("")){
                builder.downloadDir = "down_loads";
            }
            if (TextUtils.isEmpty(builder.extension) || builder.extension.equals("")){
                builder.extension = "";
            }
            if (TextUtils.isEmpty(builder.name)){
                return FileUtil.writeToDisk(is,builder.downloadDir,
                        builder.extension.toUpperCase(),builder.name);
            }else{
                return FileUtil.writeToDisk(is,builder.downloadDir,builder.name);
            }
        }
        return null;
    }



    @Override
    protected void onPostExecute(File file) {
        super.onPostExecute(file);
        if (builder != null){
            if (builder.listenerAdapter != null){
                builder.listenerAdapter.onSuccess(file.getPath());
                builder.listenerAdapter.onRequestEnd();
            }
        }
        autoInstallApk(file);
    }

    private void autoInstallApk(File file) {
        if (FileUtil.getExtension(file.getPath()).equals("apk")) {
            final Intent install = new Intent();
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.setAction(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            Latte.getApplication().startActivity(install);
        }
    }

}
